package com.example.anno;

import com.example.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
 * @Description:
 * @Author: WengYu
 * @CreateTime: 2022/06/01 00:43
 */
@Slf4j
@Aspect
@Component
public class ApiLogAspect {

    ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Pointcut("@annotation(com.example.anno.ApiLog)")
    public void log(){
    }

    @Around(value = "log()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws UnknownHostException {
        threadLocal.set(System.currentTimeMillis());
        Object result;
        String ip;
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        try {
            result = joinPoint.proceed();
            ip = IpUtil.getClientIpAddr(request);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }finally {
        }
        log.info("请求来源ip：{}",ip);
        log.info("方法执行时间：{}",(System.currentTimeMillis() - threadLocal.get()));
        return result;
    }
}
